﻿using GodSystemDAL;
using GodSystemModel;
using GodSystemCommon;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace GodSystemBLL
{
    public class UsersBLL
    {
        private static UsersDAL usersDAL = new UsersDAL();

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public DataTable GetUserList(int currentPage, int pageSize = 4, string userName = null)
        {
            DataTable dr = usersDAL.GetUserList(currentPage, pageSize, userName);
            return dr;
         
        }



        public int UpdateUserInfo(UsersModel users)
        {
            return usersDAL.UpdateUserInfo(users);
        }

        /// <summary>
        /// 根据用户ID获取数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public UsersModel GetUserInfoById(int Id)
        {
            UsersModel users  = new UsersModel();
            users.Id = Id;
            MySqlDataReader dr = usersDAL.GetUserInfoById(users);

            if (dr.Read())
            {
                users.Id = dr.GetInt32(0);
                users.Name = dr.GetString(1);
                users.Status = dr.GetInt32(2);
                users.Sex = dr.GetInt32(5);
                users.Salt = dr.GetString(6);
                users.Department = dr.GetString(7);
            }
            else
            {
                users.Id = 0;
            }

            return users;

        }
        /// <summary>
        /// 用户列表查询总数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object GetUserCount(string name = null)
        {
            return  usersDAL.GetUserCount(name);
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int AddUser(UsersModel user)
        {
            return usersDAL.Adduser(user);
        }

        /// <summary>
        /// 根据用户名检测用户是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object CheckUserNameCount(string name)
        {
            return usersDAL.CheckUserNameCount(name);
        }


        /// <summary>
        /// 检测登陆用户
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        public  bool checkUser(UsersModel users)
        {
            List<int> roleIds = new List<int>();
            
            MySqlDataReader dr = usersDAL.GetUserInfo(users);
            
            if (dr.Read())
            {
                // 是否启用
                if (dr.GetInt32(2) == 0)
                {
                    return false;
                }
                // 验证密码是否正常
                string salt = dr[6].ToString();
                string password = users.Password;
                string md5Password = Utility.GetMd5FromString(password + salt);
                if ( md5Password.Equals(dr[3].ToString()) )
                {
                    
                    GlobalData.UsersId = dr.GetInt32(0);
                    GlobalData.UsersName = users.Name;
                    GlobalData.UsersIsSuperManager = dr.GetInt32(9);
                    GlobalData.Department = dr[7].ToString();
                    GlobalData.userRoles.Clear();
                    GlobalData.userPowers.Clear();
                    GlobalData.powerList.Clear();
                    GlobalData.roleList.Clear();
                    GlobalData.powerGroup.Clear();

                    // 设置权限列表
                    PowersDAL powersDAL = new PowersDAL();
                    MySqlDataReader powerList = powersDAL.GetAllPowers();
                    if (powerList.HasRows)
                    {
                        while (powerList.Read())
                        {
                            GlobalData.powerList.Add(powerList.GetInt32(0), powerList.GetString(1));
                        }
                    }

                    // 设置角色列表
                    RolesDAL rolesDAL = new RolesDAL();
                    MySqlDataReader roleList = rolesDAL.GetRole();
                    if (roleList.HasRows)
                    {
                        while (roleList.Read())
                        {
                            GlobalData.roleList.Add(roleList.GetInt32(0), roleList.GetString(1));
                        }
                    }

                    // 如果是超级管理员，直接跳过，不用判断权限
                    if (dr.GetInt32(9) != 1)
                    {
                        GetUserRole(dr.GetInt32(0));
                        // 用户的权限ID
                        string powerIdStr = "";
                        UserrolepowerModel userrolepowerModel = new UserrolepowerModel();
                        userrolepowerModel.UserId = dr.GetInt32(0);
                        MySqlDataReader dr_power_list =  usersDAL.GetUserPowers(userrolepowerModel);
                        if (dr_power_list.HasRows)
                        {
                            while (dr_power_list.Read())
                            {
                                if (!GlobalData.userPowers.ContainsKey(dr_power_list.GetInt32(1)))
                                {
                                    string powerNode = "";
                                    int powerId = dr_power_list.GetInt32(1);
                                    if (GlobalData.powerList.ContainsKey(powerId))
                                    {
                                        powerNode = GlobalData.powerList[powerId];
                                    }
                                    GlobalData.userPowers.Add(powerId, powerNode);
                                    powerIdStr += powerId + ",";
                                }
                            }
                        }
                        // 判断权限组
                        if(!string.IsNullOrEmpty(powerIdStr))
                        {
                            List<int> groupIdsList = new List<int>();
                            string groupIdStr = "";
                            powerIdStr = powerIdStr.Substring(0, powerIdStr.Length - 1);    
                            MySqlDataReader userPowerList = powersDAL.GetPowerByPowerid(powerIdStr);
                            if (userPowerList.HasRows)
                            {
                                while (userPowerList.Read())
                                {
                                    int groupId = userPowerList.GetInt32(3);
                                    if (!groupIdsList.Contains(groupId))
                                    {
                                        groupIdsList.Add(groupId);
                                        groupIdStr += groupId + ",";
                                    }
                                }
                            }
                        
                            if (!string.IsNullOrEmpty(groupIdStr))
                            {
                                groupIdStr = groupIdStr.Substring(0, groupIdStr.Length - 1);
                                MySqlDataReader groupList = powersDAL.GetPowergroupById(groupIdStr);
                                if (groupList.HasRows)
                                {
                                    while (groupList.Read())
                                    {
                                        int powerGroupId = groupList.GetInt32(0);
                                        if (!GlobalData.powerGroup.ContainsKey(powerGroupId))
                                        {
                                            GlobalData.powerGroup.Add(powerGroupId, groupList.GetString(1));
                                        }
                                    }
                                }
                            }
              
                        }
                    }
                    else
                    {
                        GlobalData.userPowers.Add(-1, "All");
                        GlobalData.userRoles.Add(-1, "All");
                    }
                    return true;
                }
                else
                {
                    return false;
                }

            }
            return false;
        }


        public  Dictionary<int, string> GetUserRoleByUserId(int userId)
        {
            UsersModel user = new UsersModel();
            RolesDAL rolesDAL = new RolesDAL();
            Dictionary<int, string> roleIdNode = new Dictionary<int, string>();
            user.Id = userId;
            MySqlDataReader r = rolesDAL.GetUserRole(user);
            if (r.HasRows)
            {
                while (r.Read())
                {
                    roleIdNode.Add(r.GetInt32(0), r.GetString(2));
                }
            }
            return roleIdNode;
        }


        /// <summary>
        /// 获取用户的角色
        /// </summary>
        /// <param name="userId"></param>
        private static void GetUserRole(int userId)
        {
            // 获取用户角色
            RolesDAL rolesDAL = new RolesDAL();
            PowersDAL powersDAL = new PowersDAL();  
            UsersModel user = new UsersModel();
            user.Id = userId;
            MySqlDataReader r = rolesDAL.GetUserRole(user);
            if (r.HasRows)
            {
                
                string roleIds = "";
                while (r.Read())
                {
                    int roleId = r.GetInt32(2);
                    if (!GlobalData.userRoles.ContainsKey(roleId))
                    {
                        string roleName = "";
                        if (GlobalData.roleList.ContainsKey(roleId))
                        {
                            roleName = GlobalData.roleList[roleId];
                        }
                        if (!GlobalData.userRoles.ContainsKey(roleId))
                        {
                            GlobalData.userRoles.Add(roleId, roleName);
                        }
                        roleIds += roleId + ",";
                    }
                }
                // 根据用户的角色获取其权限
                roleIds = roleIds.Substring(0, roleIds.Length - 1);
                
                MySqlDataReader powerByRoleIds = powersDAL.GetPowerByRoleIds(roleIds);
                if (powerByRoleIds.HasRows)
                {
                    while (powerByRoleIds.Read())
                    {
                        int powerId = powerByRoleIds.GetInt32(2);
                        if (!GlobalData.userPowers.ContainsKey(powerId))
                        {
                            string powerNode = "";
                            if (GlobalData.powerList.ContainsKey(powerId))
                            {
                                powerNode = GlobalData.powerList[powerId];
                            }
                            GlobalData.userPowers.Add(powerId, powerNode);
                        }
                    }
                }

            }


        }

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public bool changePassword(string oldPassword, string newPassword)
        {
            UsersModel user = new UsersModel();
            user.Id = GlobalData.UsersId;
            MySqlDataReader dr = usersDAL.GetUserInfoById(user);
            if (dr.Read())
            {
                // select Id,Name,Status,Password,CreateTime,Sex,Salt,Department,Deadline,IsSuperManager from Users where Id = @Id limit 1
                string salt = dr[6].ToString();
                string originalPassword = dr[3].ToString();
                string md5Password = Utility.GetMd5FromString(oldPassword + salt);
                if (!originalPassword.Equals(md5Password))
                {
                    return false;
                }
                md5Password = Utility.GetMd5FromString(newPassword + salt);
                user.Password = md5Password;
                int affactNum = usersDAL.UpdateUserPassword(user);
                if(affactNum > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }




        public int UpdateUserPower(int userId, List<int> powerId)
        {
            UsersDAL usersDAL = new UsersDAL();
            return usersDAL.UpdateUserPower(userId, powerId);
        }

        public int UpdateUserRole(int userId, List<int> roleId)
        {
            UsersDAL usersDAL = new UsersDAL();
            return usersDAL.UpdateUserRole(userId, roleId);
        }
        
    }
}
